﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Diagnostics;

namespace Wpf.SwitchTheme.Core
{
    public class ThemeManager:IThemeManager
    {
        private Dictionary<string, ResourceDictionary> _themeList { get; set; } = new();

        public void RegisterTheme(string themeName, string resourcePath)
        {
            ResourceDictionary resourceDictionary = new()
            {
                Source =new Uri($"/Wpf.SwitchTheme.GuiResource;component/{resourcePath}",UriKind.Relative)
            };
            _themeList[themeName] = resourceDictionary;
        }

        public void ApplyTheme(string themeName)
        {
            if (_themeList.ContainsKey(themeName))
            {
                ResourceDictionary newTheme = _themeList[themeName];
                foreach (var themeDictionary in _themeList)
                {
                    Application.Current.Resources.MergedDictionaries.Remove(themeDictionary.Value);
                }
                Application.Current.Resources.MergedDictionaries.Add(newTheme);
            }
            UpdateConfig(themeName);

        }

        private void UpdateConfig(string themeName)
        {
            var config=ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["Current"].Value = themeName;
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
    }

    public interface IThemeManager
    {
        void ApplyTheme(string themeName);
        void RegisterTheme(string themeName,string resourcePath);
    }
}
